Single or multiple return statements in a function [on hold]

Posted by Juan Carlos Coto on Programmers See other posts from Programmers or by Juan Carlos Coto
Published on 2014-05-28T18:42:47Z Indexed on 2014/05/28 22:01 UTC
Read the original article Hit count: 280

When writing a function that can have several different return values, particularly when different branches of code return different values, what is the cleanest or sanest way of returning?

Please note the following are really contrived examples meant only to illustrate different styles.

Example 1: Single return

def my_function():

    if some_condition:
        return_value = 1
    elif another_condition:
        return_value = 2
    else:
        return_value = 3

    return return_value

Example 2: Multiple returns

def my_function():

    if some_condition:
        return 1
    elif another_condition:
        return 2
    else:
        return 3

The second example seems simpler and is perhaps more readable. The first one, however, might describe the overall logic a bit better (the conditions affect the assignment of the value, not whether it's returned or not).

Is the second way preferable to the first? Why?

© Programmers or respective owner

Related posts about design-patterns

Related posts about programming-languages